import { Link } from '@tanstack/react-router';
import { Card, CardHeader, CardTitle, CardContent } from '../components/ui/card';
import { Badge } from '../components/ui/badge';
import { Button } from '../components/ui/button';
import Layout from '../components/Layout';
import { usePostsQuery, useDeletePostMutation } from '../hooks/useQueries';
import { usePosts } from '../store/useStore';

export default function PostsPage() {
  const { data: posts, isLoading, error } = usePostsQuery();
  const cachedPosts = usePosts();
  const deletePostMutation = useDeletePostMutation();

  const displayPosts = posts || cachedPosts;

  const handleDelete = (id: number) => {
    if (confirm('Are you sure you want to delete this post?')) {
      deletePostMutation.mutate(id);
    }
  };

  if (isLoading && !cachedPosts.length) {
    return (
      <Layout>
        <div className="space-y-4">
          <div className="flex items-center justify-between">
            <h1 className="text-3xl font-bold">Posts</h1>
            <Button asChild>
              <Link to="/posts/create">Create Post</Link>
            </Button>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {Array.from({ length: 9 }).map((_, i) => (
              <Card key={i} className="animate-pulse">
                <CardHeader>
                  <div className="h-4 bg-muted rounded w-3/4"></div>
                  <div className="h-3 bg-muted rounded w-1/2"></div>
                </CardHeader>
                <CardContent>
                  <div className="space-y-2">
                    <div className="h-3 bg-muted rounded"></div>
                    <div className="h-3 bg-muted rounded w-5/6"></div>
                    <div className="h-3 bg-muted rounded w-4/6"></div>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        </div>
      </Layout>
    );
  }

  if (error && !cachedPosts.length) {
    return (
      <Layout>
        <div className="space-y-4">
          <div className="flex items-center justify-between">
            <h1 className="text-3xl font-bold">Posts</h1>
            <Button asChild>
              <Link to="/posts/create">Create Post</Link>
            </Button>
          </div>
          <Card className="border-destructive">
            <CardContent className="pt-6">
              <p className="text-destructive">
                Error loading posts: {error.message}
              </p>
            </CardContent>
          </Card>
        </div>
      </Layout>
    );
  }

  return (
    <Layout>
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-4">
            <h1 className="text-3xl font-bold">Posts</h1>
            <Badge variant="outline">
              {displayPosts?.length || 0} posts
            </Badge>
            {isLoading && (
              <Badge variant="secondary" className="animate-pulse">
                Loading...
              </Badge>
            )}
          </div>
          <Button asChild>
            <Link to="/posts/create">Create Post</Link>
          </Button>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {displayPosts?.map((post) => (
            <Card key={post.id} className="hover:shadow-lg transition-shadow">
              <CardHeader>
                <div className="flex items-center justify-between">
                  <Badge variant="outline">#{post.id}</Badge>
                  <Badge variant="secondary">User {post.userId}</Badge>
                </div>
                <CardTitle className="text-lg line-clamp-2">{post.title}</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  <p className="text-sm text-muted-foreground line-clamp-3">
                    {post.body}
                  </p>
                  <div className="flex gap-2">
                    <Button asChild size="sm" variant="outline">
                      <a href={`/posts/${post.id}`}>View Details</a>
                    </Button>
                    <Button 
                      size="sm" 
                      variant="destructive"
                      onClick={() => handleDelete(post.id)}
                      disabled={deletePostMutation.isPending}
                    >
                      {deletePostMutation.isPending ? 'Deleting...' : 'Delete'}
                    </Button>
                  </div>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>

        {(!displayPosts || displayPosts.length === 0) && !isLoading && (
          <Card>
            <CardContent className="pt-6 text-center">
              <p className="text-muted-foreground mb-4">No posts found</p>
              <Button asChild>
                <Link to="/posts/create">Create the first post</Link>
              </Button>
            </CardContent>
          </Card>
        )}
      </div>
    </Layout>
  );
} 